import _thread
import socket
from Constants import *

class Mensajero:

    def __init__(self):
        self.PORT = 50000
        self.s = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
        
    def iniciarSocket(self):
        try:
            self.crear()
        except:
            try:
                self.connectar()
            except:
                print("ERROR CAN'T INIT SOCKET")
            
            
        
    def crear(self):
        self.HOST = ''
        self.s.bind((self.HOST,self.PORT))
        self.s.listen(1)
        self.conn, self.addr = self.s.accept()
        self.is_server = True
        _thread.start_new_thread(self.recibir_server,())

    def connectar(self):
        self.HOST = 'localhost'
        self.is_server = False
        self.s.connect((self.HOST,self.PORT))
        _thread.start_new_thread(self.recibir_client,())
        
    def recibir_server(self):
        while True:
            data = self.conn.recv(1024)
            if not data: break
            print(data.decode())
            self.recv(data.decode())
            
    def recibir_client(self):
        while True:
            data = self.s.recv(1024)
            if not data: break
            print(data.decode())
            self.recv(data.decode())
    
    def recv(self,message):
        splitMessage = message.split(DIVISOR)
        if splitMessage[0] == CHAT :
            self.recvChat("".join(splitMessage[i] for i in range(1,len(splitMessage))))
        elif splitMessage[0] == GAME:
            self.recvGame(message)
    
    def recvChat(self,message):
        self.chat.imprimir(message)

    def recvGame(self,message):
        self.game.ejecutar(message)

    def send(self,message):
        if self.is_server:
            self.conn.send(message.encode())
        else:
            self.s.send(message.encode())

    def addChat(self,pChat):
        self.chat = pChat
        
    def addGame(self,pGame):
        self.game = pGame